#!/usr/bin/env python3
# -*-coding:utf-8-*-
# author:link
import sqlite3
from fastapi import FastAPI
import uvicorn
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import sys
import os
import time
import threading
sys.path.append(os.getcwd())
from config.db_config import *
import records

root_path=os.path.split(os.path.realpath(__file__))[0]
current_time=time.strftime('%Y-%m-%d %H:%M',time.localtime(time.time()))

lock = threading.Lock()
lock.acquire(True)

def dict_factory(cursor, row):
    d = {}
    for idx, col in enumerate(cursor.description):
        d[col[0]] = row[idx]
    return d

con = sqlite3.connect(sqlite_path,check_same_thread = False)
con.row_factory = dict_factory
cur = con.cursor()
app= FastAPI()
origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost:8080",
	"http://localhost:9528",

]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
@app.get('/caselist')
def select_all():
	cur.execute('select * from caselist_copy')
	data = cur.fetchall()
	return data

@app.get('/getcase/{id}')
def select_all(id):
	cur.execute('select * from caselist_copy where id=?',[id])
	data = cur.fetchone()
	return data

class Item(BaseModel):
	id:str
	module:str
	name:str
	method:str
	url:str
	path:str
	header:str
	isrun:str
	data:str
	expectedresult:str
	actualresult:str
	passed:str
	runtime:str

@app.post('/editcase')
def editcase(item: Item):
	cur.execute('update caselist_copy set(module,name,method,url,path,header,isrun,data,expectedresult)=(?,?,?,?,?,?,?,?,?) where id=?',
				[item.module,item.name,item.method,item.url,item.path,item.header,item.isrun,item.data,item.expectedresult,item.id])
	con.commit()
	return "success"
@app.get('/deletecase/{id}')
def editcase(id):
	cur.execute('delete FROM caselist_copy where id=?',[id])
	con.commit()
	return "success"
@app.post('/addcase')
def addcase(item: Item):
	cur.execute('INSERT INTO caselist_copy VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
				[item.id,item.module,item.name,item.method,item.url,item.path,item.header,item.isrun,item.data,item.expectedresult,item.actualresult,item.passed,item.runtime])
	con.commit()
	return "success"
@app.get('/getmaxid')
def getmaxid():
	cur.execute('select max(id) as maxid from caselist_copy')
	data = cur.fetchone()
	return data
@app.get('/getmodule/{module}')
def getmodule(module):
	if module:
		cur.execute('select * from caselist_copy where module=?',[module])
		data = cur.fetchall()
		return data
	else:
		cur.execute('select * from caselist_copy')
		data = cur.fetchall()
		return data
@app.post('/addmodule')
def addmodule(module):
	cur.execute('insert into module(module) values(?)',[module])
	con.commit()
	return "success"
@app.get('/getconfig')
def getconfig():
	cur.execute('select * from config ')
	data = cur.fetchall()
	datas = []
	for s in data:
		urldata = {'name': s.get('name'), 'url': s.get('url') + ':' + str(s.get('port'))}
		datas.append(urldata)
	return datas

@app.get('/modulelist')
def select_all():
	cur.execute('select module from caselist_copy')
	data = cur.fetchall()
	seen = set()
	new_data = []
	for d in data:
		t = tuple(d.items())
		if t not in seen:
			seen.add(t)
			new_data.append(d)
	return new_data

@app.post('/editmodule')
def editmodule(module,id):
	cur.execute('update module set(module)=(?) where id=?',[module,id])
	con.commit()
	return "success"

@app.get('/getpassed/{passed}')
def getpassed(passed):
	cur.execute('select * from caselist_copy where passed=?',[passed])
	data = cur.fetchall()
	return data

@app.get('/config')
def config():
	cur.execute('select * from config')
	data = cur.fetchall()
	return data
class Config(BaseModel):
	id:int
	name:str
	url:str
	port:int
@app.post('/addconfig')
def addconfig(items:Config):
	cur.execute('INSERT INTO config(id,name,url,port) VALUES(?,?,?,?)',
				[items.id,items.name,items.url,items.port])
	con.commit()
	return "success"

@app.get('/getcfig/{id}')
def config(id):
	cur.execute('select * from config where id=?',[id])
	data = cur.fetchone()
	return data

@app.post('/editconfig')
def editconfig(items:Config):
	cur.execute('update config set(name,url,port)=(?,?,?) where id=?',
				[items.name,items.url,items.port,items.id])
	con.commit()
	return "success"

@app.get('/deletecfg/{id}')
def deletecfg(id):
	cur.execute('delete FROM config where id=?',[id])
	con.commit()
	return "success"

@app.get('/getmaxidc')
def getmaxidc():
	cur.execute('select max(id) as maxid from config')
	data = cur.fetchone()
	return data

@app.get('/getcount/{page}&{size}')
def getcount(page:int,size:int):
	pages=page*size-size
	cur.execute('select * from caselist_copy limit ?,?',[pages,size])
	datas = cur.fetchall()
	cur.execute('select count(*) as count from caselist_copy ')
	data=cur.fetchone()
	return {'count':data.get('count'),'list':datas}

import os
@app.get('/runcase')
def runcase():
	os.system(r"pytest %s/test_all_new.py --alluredir %s/report/xml" % (root_path,root_path))
	os.system(r"allure generate --clean %s/report/xml/ -o %s/report/html/" % (root_path, root_path))
	return {'msg':"success",'time':current_time}

from common.connectdb_new import ConnectSql
@app.get('/runmodule/{module}')
def runmodule(module):
	sql=ConnectSql()
	data=sql.select_module(module)
	print(data)
	print(type(data))
	with open(root_path+'/data/getdata.json','w') as f:
		f.write(str(data))
	os.system(r"pytest %s/test_module_new.py --alluredir %s/report/xml" % (root_path,root_path))
	os.system(r"allure generate --clean %s/report/xml/ -o %s/report/html/" % (root_path, root_path))
	return {'msg':"success",'time':current_time}

@app.get('/reportsever')
def runcase():
	os.system(r"pytest %s/test_all_new.py --alluredir %s/report/xml" % (root_path,root_path))
	os.system(r"allure generate --clean %s/report/xml/ -o %s/report/html/" % (root_path, root_path))
	return "success"

if __name__ == '__main__':
	uvicorn.run(app,host='0.0.0.0',port=8000)